﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Confighelper
{
    public class MainWindowViewModel:ViewModelBase
    {
        //private Config configs;

        //public Config Configs
        //{
        //    get { return configs; }
        //    set { configs = value; }
        //}
        private List<MenuInfo> menuSource;

        public List<MenuInfo> MenuSource
        {
            get { return menuSource; }
            set { menuSource = value; }
        }




        private ObservableCollection<Config> configs;

        public ObservableCollection<Config> Configs
        {
            get
            {
                return configs;
            }
            set
            {
                this.configs = value;
                RaisePropertyChanged(nameof(Configs));
            }
        }

        private string configurationPath;

        private RelayCommand<DragEventArgs> dropCommand;

        public RelayCommand<DragEventArgs> DropCommand
        {
            get
            {
                if(dropCommand == null)
                {
                    dropCommand = new RelayCommand<DragEventArgs>((e)=>
                    {
                        //string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Confighelper.exe.config");
                        configurationPath = ((System.Array)e.Data.GetData(System.Windows.DataFormats.FileDrop)).GetValue(0).ToString();

                        GenerateKeyValue(configurationPath, false);
                    });
                }
                return dropCommand;
            }
            
        }

        private void GenerateKeyValue(string path,bool DesignerMode = true)
        {
            Configs.Clear();
            List<string> listKeys = new List<string>();
            List<Config> savedConfigs = new List<Config>();
            //In DesignMode，Load All Node
            if (DesignerMode)
            {
                listKeys = FileHelper.GetAllKeys(File.ReadAllText(path));
            }
            else
            {
                //In User Mode,Load Selected Node
                string savedPath = AppDomain.CurrentDomain.BaseDirectory + "Configs.xml";
                savedConfigs = FileHelper.Deserialize<List<Config>>(savedPath);
                listKeys = savedConfigs.Where(it => it.IsSelected == true).Select(it => it.Key).ToList();
            }

            Configuration config = ReadConfig(path);
            foreach (var key in listKeys)
            {
                Config cfg = new Config();
                cfg.Key = key;
                if (config.AppSettings.Settings[key] != null && config.AppSettings.Settings[key].Value != null)
                {
                    cfg.Value = config.AppSettings.Settings[key].Value.ToString();
                }
                cfg.IsSelected = false;
                var savedOne = savedConfigs.Where(it => it.Key == key).FirstOrDefault();
                cfg.Note = savedOne.Note;
                cfg.IsSelected = savedOne.IsSelected;
                if (cfg.Value != null)
                {
                    Configs.Add(cfg);
                }
            }
        }

        private static Configuration ReadConfig(string path)
        {
            ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = path;//AppDomain.CurrentDomain.BaseDirectory + "\\Confighelper.exe.config";  ////（引号里面的是你的配置文件的在程序的绝对路径）。
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            return config;
        }

        private RelayCommand remindCommand;

        public RelayCommand RemindCommand
        {
            get
            {
                if (remindCommand == null)
                {
                    remindCommand = new RelayCommand(() =>
                    {

                    });
                }
                return remindCommand;
            }
        }

        public MainWindowViewModel()
        {
            System.Configuration.Configuration c = ConfigurationManager.OpenExeConfiguration(
             ConfigurationUserLevel.None);
            var rawConfigs = ConfigurationManager.AppSettings;
            Configs = new ObservableCollection<Config>();
            MenuSource = new List<MenuInfo>();
            //DropCommand.Execute(null);
            InitMenu();
        }

        private void InitMenu()
        {
            MenuInfo main_file = new MenuInfo
            {
                Title = "文件",
                IsEnabled = true,
                Execute = null,
            };
            MenuInfo open_file = new MenuInfo
            {
                Title = "设计",
                IsEnabled = true,
                Execute = new RelayCommand(()=>
                {
                    OpenFileDialog dialog = new OpenFileDialog();
                    if(dialog.ShowDialog() == true)
                    {
                        string path = dialog.FileName;
                        GenerateKeyValue(path,true);
                    }
                }),
                Child = null
            };
            MenuInfo save_file = new MenuInfo
            {
                Title = "保存设计",
                Child = null,
                Execute = new RelayCommand(() =>
                {
                    FileHelper.Serialize<List<Config>>(Configs.Where(it => it.IsSelected == true).ToList());
                    MessageBox.Show("保存设计成功");
                }),
                IsEnabled = true
            };
            MenuInfo save_config = new MenuInfo
            {
                Title = "保存config",
                Child = null,
                Execute = new RelayCommand(() =>
                {
                    Configuration cfg = ReadConfig(configurationPath);
                    foreach(var item in Configs.Where(it => it.IsSelected == true).ToList())
                    {
                        cfg.AppSettings.Settings[item.Key].Value = item.Value;
                    }
                    cfg.Save();
                    MessageBox.Show("保存成功");
                }),
                IsEnabled = true
            };
            main_file.Child.Add(open_file);
            main_file.Child.Add(save_file);
            main_file.Child.Add(save_config);
            MenuSource.Add(main_file);
        }
    }
}
